package com.cml.common.serializable;

import com.cml.common.constant.MessageType;
import com.cml.common.dto.entity.Message;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 姓名：陈茂林
 * 时间：2023/10/18 8:25
 * 描述：
 */
public abstract class MessageSerializable {
    private static MessageSerializable buildMessageSerializable(Integer messageType ) throws Exception {
        Class  messageSerializableClass= MessageType.getClientMessageSerializableClass(messageType);
        if(messageSerializableClass != null){
            return (MessageSerializable) messageSerializableClass.newInstance();
        }
        return null;
    }

    public static ByteBuffer encoder(Message message) throws Exception{
        MessageSerializable messageSerializable = buildMessageSerializable(message.getMessageType());

        ByteBuffer resultByteBuffer = ByteBuffer.allocate(message.getMessageLength());
        resultByteBuffer.putInt(message.getMessageType());
        messageSerializable.doBuildEncoderMessage(message,resultByteBuffer);
        message.setMessageBuffer(resultByteBuffer);
        resultByteBuffer.flip();
        return resultByteBuffer;
    }

    public static Message decoder(SocketChannel socketChannel) throws Exception {
        try {
            ByteBuffer messageTypeBuffer = ByteBuffer.allocate(Message.MESSAGE_TYPE_LENGTH);
            socketChannel.read(messageTypeBuffer);
            messageTypeBuffer.flip();
            int messageType = messageTypeBuffer.getInt();
            MessageSerializable messageSerializable = buildMessageSerializable(messageType);
            return messageSerializable.doBuildDecoderMessage(socketChannel);
        }catch (Exception e){
            throw e;
        }
    }



    public abstract void doBuildEncoderMessage(Message message, ByteBuffer byteBuffer);

    public abstract Message doBuildDecoderMessage(SocketChannel socketChannel) throws IOException;
}
